//
//  MovieViewController.m
//  Fengly_Nuo_Movie
//
//  Created by dllo on 15/12/31.
//  Copyright © 2015年 Fengly_Nuo. All rights reserved.
//

#import "MovieViewController.h"
#import "MovieTableViewCell.h"
#import "MovieModel.h"
#import "UIImageView+WebCache.h"
#import "MovieParticularsViewController.h"
#import "MovieCollectionViewCell.h"
#import "Fengly_nuo_SQLDataBaseHandle.h"

// MARK:VIEW_CENTER_X:屏中心x轴
#define VIEW_CENTER_X self.view.center.x

// MARK:VIEW_CENTER_Y:屏中心y轴
#define VIEW_CENTER_Y self.view.center.y

// MARK:HEIGHT:屏高
#define HEIGHT self.view.frame.size.height

// MARK:WIDTH:屏宽
#define WIDTH self.view.frame.size.width

@interface MovieViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *arrModel;
//@property (nonatomic, retain) NSMutableArray *arrCollectMovies;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, retain) UIBarButtonItem *rightButtonItem;
@property (nonatomic, assign) BOOL B;

@end

@implementation MovieViewController

- (void)dealloc {
    [_collectionView release];
    [_flowLayout release];
    [_rightButtonItem release];
//    [_arrCollectMovies release];
    [_tableView release];
    [_arrModel release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 数据处理
    [self dataHandle];
    
    // 初始化
    [self initAllView];
    
    // 创建收藏数组
//    self.arrCollectMovies = [NSMutableArray array];
    
    // tableView
    [self createMovieView];
    
}



#pragma mark - 点击事件
- (void)rightButtonItemAction:(UIBarButtonItem *)buttonItem {
    
    if (!_B) {
        // 改变按钮图标
        UIImage *image = [UIImage imageNamed:@"btn_nav_list@2x.png"];
        image = [image imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
        _rightButtonItem.image = image;
        
        // collectionView
        [self createCollectionView];
        _B = YES;
    } else {
        // 改变按钮图标
        UIImage *image = [UIImage imageNamed:@"btn_nav_collection@2x.png"];
        image = [image imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
        _rightButtonItem.image = image;
        
        // tableView
        [self createMovieView];
        _B = NO;
    }
}




#pragma mark - UICollectionView Delegate
//返回item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _arrModel.count;
}

// 创建item视图对象
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MovieCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];

    MovieModel *model = _arrModel[indexPath.row];
    
    cell.model = model;
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self tableView:_tableView didSelectRowAtIndexPath:indexPath];
}



#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _arrModel.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MovieTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    MovieModel *model = _arrModel[indexPath.row];

    cell.model = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MovieParticularsViewController *movieParticularsVC = [[MovieParticularsViewController alloc] init];
    movieParticularsVC.model = _arrModel[indexPath.row];
    
    [self.navigationController pushViewController:movieParticularsVC animated:YES];
    [movieParticularsVC release];
}



/** 初始化 */
- (void)initAllView {
    self.tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 50) style:(UITableViewStylePlain)] autorelease];
    
    self.navigationItem.title = @"电影";
    
    UIImage *image = [UIImage imageNamed:@"btn_nav_collection@2x.png"];
    image = [image imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
    self.rightButtonItem = [[[UIBarButtonItem alloc] initWithImage:image style:(UIBarButtonItemStylePlain) target:self action:@selector(rightButtonItemAction:)] autorelease];
    
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 初始化
    self.collectionView = [[[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:_flowLayout] autorelease];
}

/** tableViewCell */
- (void)createMovieView {
    
    self.navigationItem.rightBarButtonItem = _rightButtonItem;
    
    [self.view addSubview:_tableView];
    //    [_tableView release];
    
    [_tableView registerClass:[MovieTableViewCell class] forCellReuseIdentifier:@"cell"];
    _tableView.delegate = self;
    _tableView.dataSource = self;
}

/** 数据处理 */
- (void)dataHandle {
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"movie" ofType:@"plist"];
//    NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:path];
//    self.arrModel = [NSMutableArray array];
//    for (NSDictionary *dic in arr) {
//        MovieModel *model = [MovieModel movieModel];
//        [model setValuesForKeysWithDictionary:dic];
//        [_arrModel addObject:model];
//    }
    
    
    NSString *str = @"http://api.douban.com/v2/movie/nowplaying?app_name=doubanmovie&client=e:iPhone4,1|y:iPhoneOS_6.1|s:mobile|f:doubanmovie_2|v:3.3.1|m:PP_market|udid:aa1b815b8a4d1e961347304e74b9f9593d95e1c5&alt=json&version=2&start=1&city=北京&apikey=0df993c66c0c636e29ecbb5344252a4a";
    // 筛选中文
    NSString *newStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 通过网络进行网络数据请求
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:newStr]];
    
    NSError *error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:&error];
    if (error) {
        NSLog(@"%@", error);
    }
    NSMutableDictionary *dic = result;
//    NSLog(@"%@", dic);
    
    NSArray *tempArr = dic[@"entries"];
    self.arrModel = [NSMutableArray array];
    for (NSDictionary *dic in tempArr) {
        MovieModel *model = [MovieModel movieModel];
        [model setValuesForKeysWithDictionary:dic];
        [_arrModel addObject:model];
    }
    
    // 数据库收藏列表的创建
    [[Fengly_nuo_SQLDataBaseHandle sharedDataBaseHandle] createTableWithTableName:@"movieList"];
}

/** collectionView */
- (void)createCollectionView {
    // 设置每个item的大小
    _flowLayout.itemSize = CGSizeMake(WIDTH / 3.6, HEIGHT / 4);
    // 设置每个item的最小列间距
    _flowLayout.minimumInteritemSpacing = 10;
    // 设置每个item的最小行间距
    _flowLayout.minimumLineSpacing = 10;
    //设置分区间隔
    _flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 129, 20);
    // 设置代理人
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    // 注册
    [_collectionView registerClass:[MovieCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionView];
    //    [_collectionView release];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
